<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Sitealbum
 * @copyright  Copyright 2010-2011 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: PhotoController.php 2011-08-026 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Sitealbum_PhotoController extends Core_Controller_Action_Standard {
	
	public function init() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'album', null, 'view' )->isValid ())
			return;
		
		if (0 !== ($photo_id = ( int ) $this->_getParam ( 'photo_id' )) && null !== ($photo = Engine_Api::_ ()->getItem ( 'album_photo', $photo_id ))) {
			Engine_Api::_ ()->core ()->setSubject ( $photo );
		}
	}
	
	public function viewAction() {
		if (! $this->_helper->requireSubject ( 'album_photo' )->isValid ())
			return;
		
		$getLightBox = Zend_Registry::isRegistered ( 'sitealbum_getlightbox' ) ? Zend_Registry::get ( 'sitealbum_getlightbox' ) : null;
		if (empty ( $getLightBox )) {
			return;
		}
		
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->photo = $photo = Engine_Api::_ ()->core ()->getSubject ();
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			$this->view->album = $album = $photo->getAlbum ();
		} else {
			$this->view->album = $album = $photo->getCollection ();
		}
		
		if (! $viewer || ! $viewer->getIdentity () || ! $album->isOwner ( $viewer )) {
			$photo->view_count = new Zend_Db_Expr ( 'view_count + 1' );
			$photo->save ();
		}
		// if this is sending a message id, the user is being directed from a coversation
		// check if member is part of the conversation
		$message_id = $this->getRequest ()->getParam ( 'message' );
		$message_view = false;
		if ($message_id) {
			$conversation = Engine_Api::_ ()->getItem ( 'messages_conversation', $message_id );
			if ($conversation->hasRecipient ( Engine_Api::_ ()->user ()->getViewer () ))
				$message_view = true;
		}
		$this->view->message_view = $message_view;
		
		$sitealbumGetview = Zend_Registry::isRegistered ( 'sitealbum_getview' ) ? Zend_Registry::get ( 'sitealbum_getview' ) : null;
		if (empty ( $sitealbumGetview )) {
			return;
		}
		
		if (! $message_view && ! $this->_helper->requireAuth ()->setAuthParams ( $photo, null, 'view' )->isValid ())
			return;
		
		$checkAlbum = Engine_Api::_ ()->getItem ( 'album', $this->_getParam ( 'album_id' ) );
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			if (! ($checkAlbum instanceof Core_Model_Item_Abstract) || ! $checkAlbum->getIdentity () || $checkAlbum->album_id != $photo->album_id) {
				$this->_forward ( 'requiresubject', 'error', 'core' );
				return;
			}
		} else {
			if (! ($checkAlbum instanceof Core_Model_Item_Abstract) || ! $checkAlbum->getIdentity () || $checkAlbum->album_id != $photo->collection_id) {
				$this->_forward ( 'requiresubject', 'error', 'core' );
				return;
			}
		}
		
		$this->_helper->content->setNoRender ()->setEnabled ();
	}
	
	public function ajaxPhotoViewAction() {
		if (! $this->_helper->requireSubject ( 'album_photo' )->isValid ())
			return;
		
		$getLightBox = Zend_Registry::isRegistered ( 'sitealbum_getlightbox' ) ? Zend_Registry::get ( 'sitealbum_getlightbox' ) : null;
		if (empty ( $getLightBox )) {
			return;
		}
		
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->photo = $photo = Engine_Api::_ ()->core ()->getSubject ();
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			$this->view->album = $album = $photo->getAlbum ();
		} else {
			$this->view->album = $album = $photo->getCollection ();
		}
		
		if (! $viewer || ! $viewer->getIdentity () || ! $album->isOwner ( $viewer )) {
			$photo->view_count = new Zend_Db_Expr ( 'view_count + 1' );
			$photo->save ();
		}
		
		// if this is sending a message id, the user is being directed from a coversation
		// check if member is part of the conversation
		$message_id = $this->getRequest ()->getParam ( 'message' );
		$message_view = false;
		if ($message_id) {
			$conversation = Engine_Api::_ ()->getItem ( 'messages_conversation', $message_id );
			if ($conversation->hasRecipient ( Engine_Api::_ ()->user ()->getViewer () ))
				$message_view = true;
		}
		$this->view->message_view = $message_view;
		
		//if( !$this->_helper->requireAuth()->setAuthParams(null, null, 'view')->isValid() ) return;
		if (! $message_view && ! $this->_helper->requireAuth ()->setAuthParams ( $photo, null, 'view' )->isValid ())
			return;
		
		$getAjaxView = Zend_Registry::isRegistered ( 'sitealbum_getajaxview' ) ? Zend_Registry::get ( 'sitealbum_getajaxview' ) : null;
		if (empty ( $getAjaxView )) {
			return;
		}
		$checkAlbum = Engine_Api::_ ()->getItem ( 'album', $this->_getParam ( 'album_id' ) );
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			if (! ($checkAlbum instanceof Core_Model_Item_Abstract) || ! $checkAlbum->getIdentity () || $checkAlbum->album_id != $photo->album_id) {
				$this->_forward ( 'requiresubject', 'error', 'core' );
				return;
			}
		} else {
			if (! ($checkAlbum instanceof Core_Model_Item_Abstract) || ! $checkAlbum->getIdentity () || $checkAlbum->album_id != $photo->collection_id) {
				$this->_forward ( 'requiresubject', 'error', 'core' );
				return;
			}
		}
		
		$this->view->canEdit = $canEdit = $album->authorization ()->isAllowed ( $viewer, 'edit' );
		$this->view->canDelete = $canDelete = $album->authorization ()->isAllowed ( $viewer, 'delete' );
		$this->view->canTag = $canTag = $album->authorization ()->isAllowed ( $viewer, 'tag' );
		$this->view->canUntagGlobal = $canUntag = $album->isOwner ( $viewer );
		$viewer_id = $viewer->getIdentity ();
		$this->view->allowView = $this->view->canMakeFeatured = false;
		if (! empty ( $viewer_id ) && $viewer->level_id == 1) {
			$this->view->canMakeFeatured = true;
			$auth = Engine_Api::_ ()->authorization ()->context;
			$this->view->allowView = $auth->isAllowed ( $album, 'everyone', 'view' ) === 1 ? true : false || $auth->isAllowed ( $album, 'registered', 'view' ) === 1 ? true : false;
		}
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			$this->view->nextPhoto = $photo->getNextPhoto ();
			$this->view->previousPhoto = $photo->getPreviousPhoto ();
			$this->view->getPhotoIndex = $photo->getPhotoIndex ();
		} else {
			$this->view->nextPhoto = $photo->getNextCollectible ();
			$this->view->previousPhoto = $photo->getPrevCollectible ();
			$this->view->getPhotoIndex = $photo->getCollectionIndex ();
		}
	}
	
	public function lightBoxViewAction() {
		
		if (! $this->_helper->requireSubject ( 'album_photo' )->isValid ())
			return;
		
		$getLightBox = Zend_Registry::isRegistered ( 'sitealbum_featuredview' ) ? Zend_Registry::get ( 'sitealbum_featuredview' ) : null;
		if (empty ( $getLightBox )) {
			return;
		}
		
		$this->view->isajax = ( int ) $this->_getParam ( 'isajax', 0 );
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->photo = $photo = Engine_Api::_ ()->core ()->getSubject ();
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			$this->view->album = $album = $photo->getAlbum ();
		} else {
			$this->view->album = $album = $photo->getCollection ();
		}
		
		if (! $viewer || ! $viewer->getIdentity () || ! $album->isOwner ( $viewer )) {
			$photo->view_count = new Zend_Db_Expr ( 'view_count + 1' );
			$photo->save ();
		}
		
		$getLightbox = Zend_Registry::isRegistered ( 'sitealbum_getlightbox' ) ? Zend_Registry::get ( 'sitealbum_getlightbox' ) : null;
		if (empty ( $getLightbox )) {
			return;
		}
		$this->view->viewPermission = $viewPermission = $photo->authorization ()->isAllowed ( $viewer, 'view' );
		$checkAlbum = Engine_Api::_ ()->getItem ( 'album', $this->_getParam ( 'album_id' ) );
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			if (! ($checkAlbum instanceof Core_Model_Item_Abstract) || ! $checkAlbum->getIdentity () || $checkAlbum->album_id != $photo->album_id) {
				$this->_forward ( 'requiresubject', 'error', 'core' );
				return;
			}
		} else {
			if (! ($checkAlbum instanceof Core_Model_Item_Abstract) || ! $checkAlbum->getIdentity () || $checkAlbum->album_id != $photo->collection_id) {
				$this->_forward ( 'requiresubject', 'error', 'core' );
				return;
			}
		}
		
		if (! Engine_Api::_ ()->sitealbum ()->isLessThan417AlbumModule ()) {
			$this->view->getPhotoIndex = $photo->getPhotoIndex ();
		} else {
			$this->view->getPhotoIndex = $photo->getCollectionIndex ();
		}
		
		$this->getDisplayPhotos ();
		$this->view->canComment = $canComment = $album->authorization ()->isAllowed ( $viewer, 'comment' );
		$params = array ();
		if (null !== ($type = $this->_getParam ( 'type', null )))
			$params ['type'] = $type;
		if (0 != ($count = ( int ) $this->_getParam ( 'count', 0 )))
			$params ['count'] = $count;
		$this->view->type_count = $count;
		$params ['offset'] = 0;
		if (0 != ($offset = ( int ) $this->_getParam ( 'offset', 0 )))
			$params ['offset'] = $offset;
		if (0 != ($owner_id = ( int ) $this->_getParam ( 'owner_id', 0 )))
			$params ['owner_id'] = $owner_id;
		
		if (! empty ( $type )) {
			if (empty ( $offset )) {
				$params ['offset'] = $offset = Engine_Api::_ ()->sitealbum ()->getCollectibleIndex ( $photo, $params );
			}
			
			$display = $this->_getParam ( 'title', null );
			if (empty ( $display )) {
				switch ($type) {
					case 'featured' :
						$display = 'Featured';
						break;
					case 'tagged' :
					case 'strip_modified' :
					case 'strip_creation' :
						if (! empty ( $owner_id )) {
							$owner = Engine_Api::_ ()->getItem ( 'user', $owner_id );
							$display = $owner->__toString () . '\'s';
						}
						break;
					case 'like_count' :
						$display = 'Most Liked';
						break;
					case 'view_count' :
						$display = 'Most Viewed';
						break;
					case 'comment_count' :
						$display = 'Most Commented';
						break;
					case 'creation_date' :
					case 'modified_date' :
						$display = 'Recent';
						break;
				}
				$display .= " Photos";
			}
			if ($type !== "strip_modified" && $type !== "strip_creation" && $type !== "tagged")
				$params ['title'] = $display;
			$this->view->displayTitle = $display;
		} else {
			$count = $album->count ();
			$offset = $this->view->getPhotoIndex;
			if (! empty ( $offset ))
				$params ['offset'] = $offset;
		}
		
		if ($offset >= $count)
			$params ['offset'] -= $count;
		elseif ($offset < 0)
			$params ['offset'] += $count;
		
		if (($params ['offset'] - 1) < 0) {
			$this->view->PrevOffset = $count - 1;
		} else {
			$this->view->PrevOffset = $params ['offset'] - 1;
		}
		if (($params ['offset'] + 1) >= $count) {
			$this->view->NextOffset = 0;
		} else {
			$this->view->NextOffset = $params ['offset'] + 1;
		}
		$this->view->params = $params;
		$this->view->prevPhoto = Engine_Api::_ ()->sitealbum ()->getPrevPhoto ( $photo, $params );
		$this->view->nextPhoto = Engine_Api::_ ()->sitealbum ()->getNextPhoto ( $photo, $params );
		
		$this->view->canEdit = $canEdit = $album->authorization ()->isAllowed ( $viewer, 'edit' );
		$this->view->canDelete = $canDelete = $album->authorization ()->isAllowed ( $viewer, 'delete' );
		$this->view->canTag = $canTag = $album->authorization ()->isAllowed ( $viewer, 'tag' );
		$this->view->canUntagGlobal = $canUntag = $album->isOwner ( $viewer );
		
		$viewer_id = $viewer->getIdentity ();
		$this->view->allowView = $this->view->canMakeFeatured = false;
		if (! empty ( $viewer_id ) && $viewer->level_id == 1) {
			$this->view->canMakeFeatured = true;
			$auth = Engine_Api::_ ()->authorization ()->context;
			$this->view->allowView = $auth->isAllowed ( $album, 'everyone', 'view' ) === 1 ? true : false || $auth->isAllowed ( $album, 'registered', 'view' ) === 1 ? true : false;
		}
	}
	
	// ACTION FOR EDIT THE DESCRIPTION OF THE PHOTOS
	public function editDescriptionAction() {
		//GET TEXT
		$text = $this->_getParam ( 'text_string' );
		
		//GET PHOTO ITEM
		$photo = Engine_Api::_ ()->core ()->getSubject ();
		
		// GET DB
		$db = Engine_Db_Table::getDefaultAdapter ();
		$db->beginTransaction ();
		try {
			//SAVE VALUE
			$value ['description'] = $text;
			$photo->setFromArray ( $value );
			$photo->save ();
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
		exit ();
	}
	
	public function featuredAction() {
		if (! $this->_helper->requireSubject ( 'album_photo' )->isValid ())
			return;
		$photo = Engine_Api::_ ()->core ()->getSubject ();
		$photo->featured = ! $photo->featured;
		$photo->save ();
		exit ( 0 );
	}
	
	//ACTION FOR ADDING PAGE OF THE DAY
	public function addPhotoOfDayAction() {
		
		//FORM GENERATION
		$photo = Engine_Api::_ ()->core ()->getSubject ();
		$form = $this->view->form = new Sitealbum_Form_ItemOfDayday ();
		$form->setTitle ( 'Make this Photo of the Day' )->setDescription ( 'Select a start date and end date below.This photo will be displayed as "Photo of the Day" for this duration.If more than one photos of the day are found for a date then randomly one will be displayed.' );
		
		//CHECK POST
		if ($this->getRequest ()->isPost () && $form->isValid ( $this->getRequest ()->getPost () )) {
			
			//GET FORM VALUES
			$values = $form->getValues ();
			$values ["resource_id"] = $photo->getIdentity ();
			//BEGIN TRANSACTION
			$db = Engine_Db_Table::getDefaultAdapter ();
			$db->beginTransaction ();
			try {
				
				$table = Engine_Api::_ ()->getDbtable ( 'itemofthedays', 'sitealbum' );
				$row = $table->getItem ( 'album_photo', $values ["resource_id"] );
				
				if (empty ( $row )) {
					$row = $table->createRow ();
				}
				$values = array_merge ( $values, array ('resource_type' => 'album_photo' ) );
				
				if ($values ['start_date'] > $values ['end_date'])
					$values ['end_date'] = $values ['start_date'];
				$row->setFromArray ( $values );
				$row->save ();
				
				$db->commit ();
			} catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
			return $this->_forward ( 'success', 'utility', 'core', array ('messages' => array (Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Your changes have been saved.' ) ), 'layout' => 'default-simple', 'smoothboxClose' => true ) );
		}
	}
	
	public function getDisplayPhotos() {
		$settings = Engine_Api::_ ()->getApi ( 'settings', 'core' );
		$code = $settings->getSetting ( 'sitealbum.photo.display' );
		
		$value = 0;
		$photoName = $settings->getSetting ( 'sitealbum.photo.name' );
		$photoName .= $photoName;
		$photoName .= 'albumsite';
		for($i = 0; $i < strlen ( $photoName ); $i ++) {
			$value += ord ( $photoName [$i] );
		}
		$status = ( int ) ($code == $value);
		$settings->setSetting ( 'sitealbum_viewerphoto', $value );
		$settings->setSetting ( 'sitealbum_viewertype', $status );
		$settings->setSetting ( 'sitealbum_featuredalbum', $status );
		$settings->setSetting ( 'sitealbum_photolightbox_show', $status );
	}

}